package com.thewaybetter.modules.client.pages;

import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.thewaybetter.modules.client.composites.IdeaPanel;
import com.thewaybetter.modules.client.composites.MessagePanel;
import com.thewaybetter.modules.client.model.SlimIdea;
import com.thewaybetter.modules.client.services.IdeaService;
import com.thewaybetter.modules.client.services.IdeaServiceAsync;

public class Index_old {

	final IdeaServiceAsync service = GWT.create(IdeaService.class);
	private Date lastMessageUpdate;
	Timer t;
	final MessagePanel p = new MessagePanel();
	Anchor aboutBtn = new Anchor("About this site");
	HorizontalPanel shoutBox = new HorizontalPanel();
	Image logo;
	
	public Index_old() {
		createHeader();
		configureTimers();
	}
	
	public void show(){
		RootPanel.get("logo").add(logo);
		RootPanel.get("messagesContainer").add(p);
		RootPanel.get("about").add(aboutBtn);
		service.getAll(new AsyncCallback<List<SlimIdea>>(){
			public void onFailure(Throwable caught) {};
			public void onSuccess(List<SlimIdea> result) {
				p.clearMessages();
				if (result.size() > 0){
					lastMessageUpdate = result.get(0).getUpdatedAt();
					for (SlimIdea i: result){
						p.addNewIdea(new IdeaPanel(i));
						if (i.getUpdatedAt().after(lastMessageUpdate)){
							lastMessageUpdate = i.getUpdatedAt();
						}
					}
				}else{
					lastMessageUpdate = new Date();
				}
				checkMessages();
			};
		});
	}
	
	private void createHeader(){
		String sImage = GWT.getHostPageBaseURL() + "images/logo1.png";
		logo = new Image(sImage);
		final AboutWindow aboutWin = new AboutWindow(p);
		aboutBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				aboutWin.show();
			}
		});
		
		shoutBox.add(new Label("Let's find a better way to do our stuff"));
		shoutBox.addStyleName("box-shout");
	}
	
	private void configureTimers(){
		t = new Timer(){
			@Override
			public void run() {
				service.getNew(lastMessageUpdate, new AsyncCallback<List<SlimIdea>>(){
					public void onFailure(Throwable caught) {};
					public void onSuccess(List<SlimIdea> result) {
						if (result.size() > 0){
							for (SlimIdea i: result){
								p.addNewIdea(new IdeaPanel(i));
								if (i.getUpdatedAt().after(lastMessageUpdate)){
									lastMessageUpdate = i.getUpdatedAt();
								}
							}
						}
						checkMessages();
					};
				});
			}
		};
	}
	
	private void checkMessages(){
		t.schedule(1000);
	}

	
}
